/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.base;

import java.util.List;
import org.webos.java.base.users.*;
import org.urchr.web.db.DBSession;
import org.webos.java.base.db.User;
import org.webos.java.base.db.apps.Keychain;
import org.webos.java.base.utils.CryptoUtil;
import org.webos.java.root.Log;

/**
 *
 * @author Kostya
 */
public class UserManager {
    private static UserProvider provider = null;

    /**
     * @return the provider
     */
    public static UserProvider getProvider() {
        return provider;
    }

    /**
     * @param aProvider the provider to set
     */
    public static void setProvider(UserProvider aProvider) {
        provider = aProvider;
    }

    public static boolean passwordChanged(String aID, String oldPassword, String newPassword){
        DBSession dbs = new DBSession();
        try {
            User user = (User) dbs.createQuery("from User where code=:code").
                    setString("code", aID).uniqueResult();
            if(user==null)
                return false;
            List<Keychain> pass = dbs.createQuery("from Keychain where user=:user").
                    setEntity("user", user).list();
            dbs.begin();
            for (Keychain keychain : pass) {
                keychain.setPassword(CryptoUtil.encode(newPassword, CryptoUtil.decode(oldPassword, keychain.getPassword())));
                dbs.save(keychain);
            }
            dbs.commit();
            for (int i = 0; i < SessionManager.getSessionCount(); i++) {
                Session session = SessionManager.getSessionAt(i);
                if(session.getUserCode().equals(aID))
                    session.setPassword(newPassword);

            }
            return true;
        } catch (Throwable t) {
            dbs.rollback();
            Log.error("UserManager", "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        } finally {
            dbs.close();
        }
        return false;
    }
}
